﻿namespace MinefieldCheat
{
    internal class CMinefieldMap
    {
        private readonly string[] _grid;
        private readonly int _height;
        private readonly int _width;

        public CMinefieldMap( string[] grid )
        {
            _grid = grid;
            _width = _grid[0].Length;
            _height = _grid.Length;
        }

        public int Height
        {
            get { return _height; }
        }

        public int Width
        {
            get { return _width; }
        }

        private bool IsPositionOffGrid(int x, int y)
        {
            if (x < 0)
                return true;
            if (y < 0)
                return true;
            if (x >= Width)
                return true;
            if (y >= Height)
                return true;
       
            if (x >= _grid[y].Length)
                return true;                  // actually the grid is invalid because one line is too short!

            return false;
        }

        private char GetCharAtPosition(int x, int y)
        {
            if (IsPositionOffGrid(x, y))
                return ' ';

            return _grid[y][x];
        }

        private bool IsBombAtPosition( int x, int y )
        {
            if (GetCharAtPosition(x, y) == '*')
                return true;

            return false;
        }

        public int CountBombsAroundPosition( int x, int y )
        {
            int count = 0;
            for ( int yy = -1 ; yy < 2 ; yy++)
                for ( int xx = -1 ; xx < 2 ; xx++)
                {
                    if ( !( yy == 0 && xx == 0 ) )
                    {
                        if (IsBombAtPosition(x + xx, y + yy))
                            count++;
                    }
                }

            return count;
        }
    }
}
